package com.numberone.master.modules.orders.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.numberone.master.common.yunzhanghu.TixianUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.numberone.master.common.config.Global;
import com.numberone.master.common.persistence.Page;
import com.numberone.master.common.web.BaseController;
import com.numberone.master.common.utils.DoubleUtil;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.modules.orders.entity.RechargeOrder;
import com.numberone.master.modules.orders.entity.WithdrawalsOrder;
import com.numberone.master.modules.orders.service.WithdrawalsOrderService;
import com.numberone.master.modules.profit.entity.AccountInfo;
import com.numberone.master.modules.profit.service.AccountInfoService;
import com.numberone.master.modules.sys.utils.UserUtils;

/**
 * 提现Controller
 * @author ck
 * @version 2018-03-27
 */
@Controller
@RequestMapping(value = "${adminPath}/orders/withdrawalsOrder")
public class WithdrawalsOrderController extends BaseController {

	@Autowired
	private WithdrawalsOrderService withdrawalsOrderService;
	
	@Autowired
	private AccountInfoService accountInfoService;

	 /**
     * 根据id查询一条数据
     * @param id
     * @return
     */
	@ModelAttribute
	public WithdrawalsOrder get(@RequestParam(required=false) String id) {
		WithdrawalsOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = withdrawalsOrderService.get(id);
		}
		if (entity == null){
			entity = new WithdrawalsOrder();
		}
		return entity;
	}

	 /**
     * list列表
     * @param withdrawalsOrder
     * @param request
     * @param response
     * @param model
     * @return
     */
	@RequiresPermissions("orders:withdrawalsOrder:list")
	@RequestMapping(value = {"list", ""})
	public String list(WithdrawalsOrder withdrawalsOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		String officeId = UserUtils.getUser().getOffice().getId();
		if(!StringUtils.equals("1", officeId)){
			withdrawalsOrder.setOfficeId(officeId);
		}
		Page<WithdrawalsOrder> page = withdrawalsOrderService.findPage(new Page<WithdrawalsOrder>(request, response), withdrawalsOrder); 
		model.addAttribute("page", page);
		return "modules/orders/withdrawalsOrderList";
	}
	
	/**
	 * 审核列表
	 * @param withdrawalsOrder
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("orders:withdrawalsOrder:list")
	@RequestMapping(value = {"withdrawalsExamineList", ""})
	public String withdrawalsExamineList(WithdrawalsOrder withdrawalsOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		withdrawalsOrder.setState("1");
		Page<WithdrawalsOrder> page = withdrawalsOrderService.findPage(new Page<WithdrawalsOrder>(request, response), withdrawalsOrder); 
		model.addAttribute("page", page);
		return "modules/orders/withdrawalsExamineList";
	}
	
	/**
	 * 提现审核
	 * @param ids
	 * @param rechargeState
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("orders:withdrawalsOrder:examine")
	@RequestMapping(value = "examine")
	public String examine(String ids,String rechargeState,RedirectAttributes redirectAttributes) {
		if(StringUtils.isBlank(ids)){
			addMessage(redirectAttributes, "审核失败！id为空。");
			return "redirect:" + adminPath + "/orders/withdrawalsOrder/withdrawalsExamineList?repage";
		}
		String[] exid = ids.split(",");
		int num = 0;
		for (int i = 0; i < exid.length; i++) {
			WithdrawalsOrder o = withdrawalsOrderService.get(exid[i]);
			if(o == null){
				addMessage(redirectAttributes, "审核失败！未查询到提现订单。");
				return "redirect:" + adminPath + "/orders/withdrawalsOrder/withdrawalsExamineList?repage";
			}
			if(StringUtils.equals("3", o.getState()) || StringUtils.equals("2", o.getState())){
				addMessage(redirectAttributes, "审核失败！此订单已经审核过。");
				return "redirect:" + adminPath + "/orders/withdrawalsOrder/withdrawalsExamineList?repage";
			}
			WithdrawalsOrder rechargeLs = new WithdrawalsOrder();
			if(StringUtils.equals("2", rechargeState)){
				rechargeLs.setRemarks("审核通过");
			}else{
				rechargeLs.setRemarks("审核不通过");
			}
			rechargeLs.setId(exid[i]);
			rechargeLs.setUpdateById(UserUtils.getUser().getId());
			rechargeLs.setUpdateDate(new Date());
			rechargeLs.setState(rechargeState);
			withdrawalsOrderService.update(rechargeLs);
			//取消的操作设置为失败订单
			if(StringUtils.equals("3", rechargeState)){
				AccountInfo accountInfo = accountInfoService.getAccountByOfficeId(o.getOfficeId());
				accountInfo.setOfficeId(Long.valueOf(o.getOfficeId()));
				String price = o.getWithdrwalsAmount();//提现金额
				Double kamt = DoubleUtil.add(Double.valueOf(accountInfo.getKamt()), Double.valueOf(price));
				Double damt = DoubleUtil.sub(Double.valueOf(accountInfo.getDamt()), Double.valueOf(price));
				accountInfo.setKamt(String.valueOf(kamt));
				accountInfo.setDamt(String.valueOf(damt));
				accountInfoService.update(accountInfo);
			}
			num++;
		}
		addMessage(redirectAttributes, "成功审核<"+num+">条提现订单数据。");
		return "redirect:"+adminPath+"/orders/withdrawalsOrder/withdrawalsExamineList?repage";
	}

	/**
	 * 查询审核中的订单
	 */
	public void queryYunzhuangHuOrder(){
		WithdrawalsOrder order=new WithdrawalsOrder();
		order.setState("1");
		System.out.println(order);
		System.out.println(withdrawalsOrderService);
		List<WithdrawalsOrder> list = withdrawalsOrderService.findList(order);
		WithdrawalsOrder withdrawalsOrder ;
		for (int i = 0; i < list.size(); i++) {
			withdrawalsOrder =  list.get(i);
			Map<String,Object> map= TixianUtil.queryOrder(withdrawalsOrder.getOrderNo(),"银行卡");//目前固定为银行卡
			handleResult(map,withdrawalsOrder);
		}


	}

	/**
	 * 处理订单
	 * @param result
	 * @param withdrawalsOrder
	 */
	private void handleResult(Map<String, Object> result, WithdrawalsOrder withdrawalsOrder) {
		if(result==null){
			logger.info("----------云账号未查询到订单号为"+withdrawalsOrder.getOrderNo()+"的信息--------------");
			return;
		}
		AccountInfo accountInfo = accountInfoService.getAccountByOfficeId(withdrawalsOrder.getOfficeId());
		//可提余额
		Double kamtMoney = Double.valueOf(accountInfo.getKamt());
		//未到账余额
		Double damt = Double.valueOf(accountInfo.getDamt());

		Gson gson = new Gson();
		Map<String, Object> tokenData = gson.fromJson(result.get("tokenData").toString(), result.getClass());
		System.out.println("tokenData---"+tokenData);
		String code=tokenData.get("code").toString();
		if(!code.equals("0000")){
			logger.info("-------订单号为:"+withdrawalsOrder.getOrderNo()+"错误信息为"+result.get("message")+"----------");
		}
		boolean flag=false;
		Map<String,Object> data= (Map<String, Object>) tokenData.get("data");
		System.out.println("data---"+data);
		String status=data.get("status").toString();
		if(status.equals("1")){
			withdrawalsOrder.setState("4");
			withdrawalsOrder.setRemarks("物联网卡提现_成功");
			accountInfo.setDamt(String.valueOf(DoubleUtil.sub(damt, Double.valueOf(withdrawalsOrder.getWithdrwalsAmount()))));
			flag=true;
		}else if(status.equals("2") || status.equals("9") ){
			withdrawalsOrder.setState("4");
			withdrawalsOrder.setRemarks("提现失败---"+data.get("status_message").toString()+"---"+data.get("status_detail_message").toString());
			//可提余额加上提现金额
			accountInfo.setKamt(String.valueOf(DoubleUtil.add(kamtMoney, Double.valueOf(withdrawalsOrder.getWithdrwalsAmount()))));
			//未到账要减去
			accountInfo.setDamt(String.valueOf(DoubleUtil.sub(damt, Double.valueOf(withdrawalsOrder.getWithdrwalsAmount()))));
			flag=true;
		}
		if(flag){
			accountInfoService.update(accountInfo);
			withdrawalsOrderService.update(withdrawalsOrder);
		}


	}



}